package cn.edu.sdjzu.xg23.kcsj01_backend.controller;

import cn.edu.sdjzu.xg23.kcsj01_backend.entity.authority.Permission;
import cn.edu.sdjzu.xg23.kcsj01_backend.entity.authority.Role;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.RoleService;
import cn.edu.sdjzu.xg23.kcsj01_backend.utils.Result;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static cn.edu.sdjzu.xg23.kcsj01_backend.utils.ResultCodeEnum.SYSTEM_ERROR;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 获取角色列表
     */
//    @PreAuthorize("hasAuthority('system:role:search')")
    @PostMapping("/search")
    public Result searchRoles(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestBody(required = false) Role role) {

        PageInfo<Role> pageInfo = roleService.selectRolesByCondition(pageNum, pageSize, role);
        return Result.success(pageInfo);
    }



    /**
     * 新增角色（包含权限分配）
     */
    @PreAuthorize("hasAuthority('system:role:add')")
    @PostMapping
    public Result add(@RequestBody Role role) {
        boolean result = roleService.insertRole(role);
        return result ? Result.success() : Result.error(SYSTEM_ERROR);
    }

    /**
     * 修改角色（包含权限分配）
     */
    @PreAuthorize("hasAuthority('system:role:update')")
    @PutMapping
    public Result update(@RequestBody Role role) {
        boolean result = roleService.updateRole(role);
        return result ? Result.success() : Result.error(SYSTEM_ERROR);
    }

    /**
     * 删除角色
     */
    @PreAuthorize("hasAuthority('system:role:delete')")
    @DeleteMapping("/{roleId}")
    public Result delete(@PathVariable Long roleId) {
        boolean result = roleService.deleteRoleById(roleId);
        return result ? Result.success() : Result.error(SYSTEM_ERROR);
    }

    // 获取角色已有权限列表
//    @PreAuthorize("hasAuthority('system:role:getPermissions')")
    @GetMapping("/{roleId}/permissions")
    public Result getRolePermissions(@PathVariable Long roleId) {
        List<Permission> permissions = roleService.selectPermissionsByRoleId(roleId);
        return Result.success(permissions);
    }

}